<template>
  <div class="search-page">
    <header class="search-header">
		<div class="back-btn" @click="goBack()">
			<i class="fa fa-arrow-left"></i>
		</div>
		<input
			type="text"  
			class="search-input"
			v-model="searchQuery"
			placeholder="搜索商家或商品"
		/>
	     <!-- text：输入框类型：文本框
		  class="search-input"给输入框的CSS类名，定义样式
		  v-model双向绑定-->
		<button class="search-button" @click="performSearch">
        <i class="fa fa-search"></i>
      </button>
    </header>
    <!-- 搜索结果区域 -->
    <div class="search-results">
      <p v-if="searchResults.length === 0">没有找到相关结果。</p>
      <ul v-else>
        <li v-for="result in searchResults" :key="result.id">
          {{ result.name }} - {{ result.description }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

export default {
  name: "Search",
  setup() {
    const route = useRoute();
    const router = useRouter();
	const searchQuery = ref(''); // 定义为响应式引用
	const searchResults = ref([]);

    watch(() => route.query.q, (newQuery) => {
      searchQuery.value = newQuery;
      if (newQuery) {
        performSearch();
      }
    }, { immediate: true });

    const performSearch = async () => {
      try {
        const response = await axios.post('BusinessController/searchBusiness', { query: searchQuery.value });
        if (response && response.data) {
			searchResults.value = response.data;
        } else {
          console.error('Unexpected response structure:', response);
          this.searchResults = []; // 如果响应结构不正确，清空结果
        }
      } catch (error) {
        console.error('搜索出错:', error);
			searchResults.value = []; // 搜索出错时清空结果
      }
    };

    const goBack = () => {
      router.back();
    };

    return {
		searchQuery, // 返回响应式引用
        searchResults,
        performSearch,
        goBack,
    };
  },
};
</script>

<style scoped>
.search-page {
  width: 100%;
  height: 100%;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #ddd;
  user-select: none;
}

.search-input {
  flex-grow: 1;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  font-size: 16px;
}

.search-button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  position: fixed;
}

.search-button i {
  margin-right: 5px;
}

.search-results {
  padding: 20px;
}

.search-results ul {
  list-style-type: none;
  padding: 0;
}

.search-results li {
  margin-bottom: 10px;
}
.wrapper .back-btn {
  position: fixed;
  top: 2vw;
  left: 2vw;
  font-size: 4vw;
  color: #fff;
  cursor: pointer;
  user-select: none;
  z-index: 1000;
}
</style>